fs = require 'fs'
formidable = require 'formidable'
ObjectId = require('mongoose').Types.ObjectId

fileServ = require './file_serv'
{getTime2,getDateString,getDateString2} = require '../utils/time_utils'

{findComp} = require '../comp/comp_serv'

# 返回图片URL
# result 组件配置信息
# folder_name 文件夹名字
# new_file_name 新的文件名字
getImgUrl = (result, folder_name, new_file_name) ->
  if 0 is (result?.length or 0)
    return ''
  return result?[0]?.upload?.file_url_prefix + "/" + folder_name + "/" + new_file_name

#文件上传
exports.upload = (req, res, cbf) ->

  # 上传组件ID
  comp_id = req.params?.comp_id or req.query?.comp_id or req.body?.comp_id
  # 图片地址返回类型  不传时为普通上传，传入时为富文本上传
  img_url_type = req.params?.img_url_type

  # 文件保存路径参数(如果传入产品代码)
  # path_params =  req.query?.prod_code or req.params?.prod_code or ""

  # 根据组件id查询数据库上传组件的配置项
  findComp {comp_id: comp_id}, (error, result) ->
    if error
      return cbf error, null

    if 0 is (result?.length or 0)
      return cbf '组件不存在', null

    console.log result

    rItem = result?[0]

    # 创建上传表单
    form = new (formidable.IncomingForm)
    # 设置编辑
    form.encoding = 'utf-8'
    # 设置上传目录
    form.uploadDir = rItem?.upload?.upload_path
    # 保留后缀
    form.keepExtensions = true
    # 文件大小
    form.maxFieldsSize = rItem?.upload?.file_size
    # 设置所以文件的大小总和
    # form.maxFields = 1000;

    # 创建上传路径的文件夹
    folder_name = rItem?.upload?.folder_name or ""
    if folder_name and "" isnt folder_name
      # 文件保存路径
      path = form.uploadDir + "/" + folder_name
      # 文件访问地址(没有前缀)
      path_url = folder_name
    if !(fs.existsSync path)
      fs.mkdirSync path
    # 上传文件到相应的产品代码目录下
    # if path_params and "" isnt path_params
    #   # 文件保存路径
    #   path = path + "/" + path_params
    #   # 文件访问地址(没有前缀)
    #   path_url = path_url + "/" + path_params
    #   if !(fs.existsSync path)
    #     fs.mkdirSync path

    # 解析文件以及参数
    form.parse req, (err, fields, files) ->
      if err
        return cbf err, null
      upload_file = []
      # 遍历所有文件
      for item of files
        # 文件名字
        file_name = files[item].name
        # 文件类型
        # file_type = files[item].type
        # 文件后缀
        subFix = file_name.substring(file_name.lastIndexOf(".")+1)
        # 文件类型要与组件的后缀匹配
        if (rItem.upload.file_subfix.indexOf subFix) == -1
          return cbf '文件格式不正确',null

        if !!img_url_type
          # 原文件名
          new_file_name = file_name
        else
          # 按照日期命名
          if rItem.upload.rename_rules == "1"
            # 新文件名
            new_file_name = getDateString2(new Date())+getTime2(new Date()) + Math.ceil(Math.random()*1000000) + "." + subFix
          else
            # 原文件名
            new_file_name = file_name

        # 文件存放地址
        newPath = path + "/" + new_file_name
        # 将文件写在虚拟目录下
        fs.renameSync files[item].path, newPath

        # 将文件全部信息保存到数据库
        params =
          # file_id:new ObjectId()
          file_name: files[item].name.substring(0,files[item].name.indexOf("."))
          rename_file_name: new_file_name
          file_type: subFix
          file_size: files[item].size
          file_path: newPath
          file_url: rItem?.upload?.file_url_prefix + "/" + path_url + "/" + new_file_name
          file_date: getDateString(new Date())

        upload_file.push params
      # 将文件保存到数据库
      fileServ.batSaveFile upload_file, (err, res)->
        if err
          return cbf '文件保存出错', null

        if !!img_url_type
          return cbf null, getImgUrl result, folder_name, new_file_name
        else
          return cbf null, res

# 文件下载示例
exports.download = (req, res) ->
  path = 'public/upload/file.txt'
  # 文件存储的路径
  # filename:设置下载时文件的文件名，可不填，则为原名称
  res.download filepath, filename
  return

# 上传excel表格
exports.upload2 = (req, res, cbf) ->
  # 从session中读取商家ID、商家名称
  company_id = req.session?.user_back?.company_id or ''
  merchant_name = req.session?.user_back?.merchant_name or ''

  # 创建上传表单
  form = new (formidable.IncomingForm)
  # 保留后缀
  form.keepExtensions = true

  # 解析文件以及参数
  form.parse req, (err, fields, files) ->
    if err
      return cbf err, null
    upload_file = []
    # 遍历所有文件
    for item of files
      # 文件名字
      file_name = files[item].name
      # 文件类型
      # file_type = files[item].type
      # 文件后缀
      subFix = file_name.substring(file_name.lastIndexOf(".")+1)

      # upload_file.push params
      return cbf null,files